package cn.msqweb.service.impl;



import cn.hutool.core.util.ObjectUtil;
import cn.msqweb.constant.BusinessEnum;
import cn.msqweb.entity.IndexImg;
import cn.msqweb.entity.Prod;
import cn.msqweb.ex.handler.ex.BusinessException;
import cn.msqweb.feign.StoreProductFeign;
import cn.msqweb.mapper.IndexImgMapper;

import cn.msqweb.model.Result;
import cn.msqweb.service.IndexImgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService {

    @Autowired
    private IndexImgMapper indexImgMapper;

    @Autowired
    private StoreProductFeign storeProductFeign;

    @Override
    public Boolean saveIndexImg(IndexImg indexImg) {
        indexImg.setShopId(1L);
        indexImg.setCreateTime(new Date());
        return indexImgMapper.insert(indexImg)>0;
    }

    @Override
    public IndexImg queryIndexImgInfoById(Long imgId) {
        // 根据标识查询轮播图信息
        IndexImg indexImg = indexImgMapper.selectById(imgId);
        // 获取关联商品标识
        Long prodId = indexImg.getProdId();
        // 判断是否有值
        if (ObjectUtil.isNotNull(prodId)) {
            // 说明：当前轮播图关联了商品
            // 远程调用：根据商品标识查询商品信息
            Result<List<Prod>> result = storeProductFeign.getProdListByIds(Arrays.asList(prodId));
            // 判断操作结果
            if (result.getCode().equals(BusinessEnum.OPERATION_FAIL.getCode())) {
                throw new BusinessException(BusinessEnum.OPERATION_FAIL.getDesc());
            }
            // 获取数据
            List<Prod> prodList = result.getData();
            Prod prod = prodList.get(0);
            indexImg.setPic(prod.getPic());
            indexImg.setProdName(prod.getProdName());
        }
        return indexImg;
    }
}
